package com.starblink.android.guang

import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.GsonUtils
import com.google.firebase.messaging.Constants.MessagePayloadKeys
import com.google.gson.reflect.TypeToken
import com.starblink.android.basic.appupdate.AppUpdateManager
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.bridge.BridgeCommand
import com.starblink.android.basic.bridge.BridgeUtil
import com.starblink.android.basic.config.showTrackLogDss
import com.starblink.android.basic.data.GaidReportManager
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.navigation
import com.starblink.android.basic.guide.SkNoviceManage
import com.starblink.android.basic.guide.bean.SkGuideEnum
import com.starblink.android.basic.network.base.BaseSiteSwitch
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.sensorsdata.spm.service.SpmUploadService
import com.starblink.android.basic.urllink.PullUpPageUtils
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.FlowCountDownTimer
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.guang.databinding.ActivityMainBinding
import com.starblink.android.guang.push.FCMUtils
import com.starblink.android.guang.widget.cstnavbar.CustomNavBarConfig
import com.starblink.android.guang.widget.cstnavbar.PartNavBar
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.storage.SkStorage
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.home.subscription.HomeSubscriptionFragment
import com.starblink.home.ui.HomeI
import com.starblink.home.ui.NavHomeFragment
import com.starblink.library.widget.novice_guide.control.GuidePopStatusControl
import com.starblink.mine.ui.NavMineFragment
import com.starblink.rocketreserver.fragment.SiteVOF
import com.starblink.search.category.ui.SearchCategoryFragment
import kotlin.system.exitProcess


@Route(path = RoutePage.Main.MAIN_ACTIVITY)
class MainActivity : BaseTVMActivity<ActivityMainBinding, MainViewModel>(), HomeI {

    lateinit var fragmentList: List<Fragment>
    private var intentStart: Intent? = null
    private lateinit var mNavBar: PartNavBar

    override fun initViewBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun isStatusBarLightMode(): Boolean = false

    @SuppressLint("UseCompatLoadingForColorStateLists")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

//        if (BuildConfig.DEBUG) {
//            SkNoviceManage.resetVoiceGuide()
//        }
        //处理FCM推送消息
        handleFcmMessage(intent.extras)
        //启动页往这里跳转
        handleActivePageJumpUrl(intent.extras)
        //配置导航栏
        mNavBar = PartNavBar(viewBinding).apply {
            btmNavBarInit()
        }
        //处理eventbus
        handleFlowBus()
        //处理站点
        handleSiteDialog()
        //初始化通知相关内容 不在这里触发了 在NavHomeFragment接口请求完后回调触发 解决引导不显示问题
//        initNotification()
        //初始化默认的Fragment
        initFragment()


        // 开机屏 和 首页弹窗 图片预热缓存 3 开机屏图片 4 首页广告图片
        viewModel.getResourceScreenOrHomeImage()
        //校验是否有类目
        viewModel.checkIsExistCategory()
        //处理外链 APP未启动
        handleSchemeOrDeepLink(intent)
        //判断是否要更新
        handleAppUpdate()
        //启动Spm轮询服务
        startSpmService()

        viewModel.syncSubsInfo()

        GaidReportManager.reportDeviceId(this)
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.subsLD.observe(this) {
            CustomNavBarConfig.isNewDay = it
            mNavBar.loadNavImgRes()
        }


    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        SKLogger.e("dss", "MainActivity-onNewIntent, intent.extras=${intent.extras}")
//        val bundle: Bundle? = intent.extras
//        bundle?.let {
//            for (key in bundle.keySet()) {
//                val value = bundle.get(key)
//                SKLogger.e("dss", "Key: $key Value: $value
//            }
//        }
        // 对于推送消息：getguang://guang/home?type=mall&recTop=true，点击后会回调onNewIntent方法，参数如下：
        // Key: NTeRQWvye18AkPd6G Value: getguang://guang/main/main_activity?type=mall&recTop=true
        handleFcmMessage(intent.extras)
        //处理外链 APP已启动
        handleSchemeOrDeepLink(intent)
    }

    override fun onResume() {
        isFront = true
        super.onResume()
        GTrackerAssistUtils.navigationUrl = GTrackerAssistUtils.MAIN_URL
    }

    /**
     * 处理APP更新
     */
    private fun handleAppUpdate() {
        AppUpdateManager.updateInfoLiveData.observe(this) {
            val updateInfo = it.getContentIfNotHandled()
            if (updateInfo == null) {
                SKLogger.e("dss", "获取更新信息失败或者已经处理过检查更新事件，进入下一步")
            } else {
                if (updateInfo.needUpdate) {
                    viewBinding.btmNavImg2.post {
                        SKLogger.e("dss", "显示更新弹窗")
                        GuidePopStatusControl.pushPopWindow(
                            context = this,
                            parent = viewBinding.root,
                            updateInfo = updateInfo,
                            dismissCallBack = {
                                SKLogger.e("dss", "更新弹窗关闭，进入下一步")
                            }
                        )
                    }
                } else {
                    SKLogger.e("dss", "无需更新，进入下一步")
                }
            }
        }
    }

    /**
     * 处理FCM推送消息
     * @note
     * APP未启动，在MainActivity的onCreate中处理通知消息的数据载荷
     * APP处于后台，在MainActivity的onNewIntent中处理通知消息的数据载荷
     */
    private fun handleFcmMessage(bundle: Bundle?) {
        SKLogger.e("dss", "MainActivity-onCreate")
        // 仅当bundle包含Fcm通知消息数据载荷时，进行处理
        if (bundle == null || bundle.getString(MessagePayloadKeys.MSGID).isNullOrEmpty()) return
        SKLogger.e("dss", "MainActivity-handleFcmMessage")
        for (key in bundle.keySet()) {
            val value = bundle.get(key)
            SKLogger.e("dss", "Key: $key Value: $value")
        }

        //        10:53:49.757  E  [, , 0]:Key: google.delivered_priority Value: normal
//        10:53:49.757  E  [, , 0]:Key: google.sent_time Value: 1698461623772
//        10:53:49.757  E  [, , 0]:Key: google.ttl Value: 604800
//        10:53:49.757  E  [, , 0]:Key: google.original_priority Value: normal
//        10:53:49.757  E  [, , 0]:Key: analysis Value: 251
//        10:53:49.757  E  [, , 0]:Key: xRoute Value: {"url":"getguang://guang/stores_home_page?id=8_322920836651921408"}
//        10:53:49.757  E  [, , 0]:Key: from Value: 132150157594
//        10:53:49.757  E  [, , 0]:Key: com.google.firebase.iid.WakeLockHolder.wakefulintent Value: true
//        10:53:49.757  E  [, , 0]:Key: google.message_id Value: 0:1698461623781410
//        null29dc105e29dc
//        10:53:49.758  E  [, , 0]:Key: gcm.n.analytics_data Value: Bundle[mParcelledData.dataSize=100]
//        10:53:49.758  E  [, , 0]:Key: collapse_key Value: com.starblink.android.guang

        SKLogger.e("dss", "埋点：App从Push打开", showTrackLogDss)
        try {
            val params = mutableMapOf<String, String>()
            bundle.getString("analysis")?.let {
                params["analysis"] = it
            }
            bundle.getString(MessagePayloadKeys.MSGID)?.let {
                params["firebaseMsgId"] = it
            }
            SpmTrackHandler.addSingleTrackData(
                SkAntEntity(
                    event = TrackEvent.appLifeCycle.value,
                    spmCnt = GTrackerAssistUtils.fetchElementValue(
                        0,
                        SpmElementDef.AppOpenFromPush
                    ),
                    params = params
                )
            )
        } catch (e: Exception) {
        }

        val xRoute = bundle.getString(FCMUtils.KEY_XROUTE) // 获取xRoute数据
        if (xRoute.isNullOrEmpty().not()) {
            val dataMap: Map<String, Any> = GsonUtils.fromJson(
                xRoute,
                object : TypeToken<Map<String, Any>>() {}.type
            )
            (dataMap["url"] as? String?)?.let {
                SKLogger.e("dss", "跳转URL：$it")
                PullUpPageUtils.routePageIntercept4Url(
                    activity = mActivity,
                    url = it,
                    externalPull = false
                )
            }
        }
    }

    /**
     * 启动页往这里跳转
     */
    private fun handleActivePageJumpUrl(bundle: Bundle?) {
        bundle?.let {
            var url = it.getString("jumpUrl")
            if (!url.isNullOrBlank()) {
                FlowCountDownTimer(time = 1).start(callBack = {
                }, onFinish = {
                    PullUpPageUtils.routePageIntercept4Url(
                        activity = mActivity,
                        url = url
                    )
                })
            }
        }
    }


    //初始化默认的Fragment
    private fun initFragment() {
        fragmentList = listOf(
            NavHomeFragment.obtainFragment(),
            SearchCategoryFragment.obtainFragment(),
            HomeSubscriptionFragment.newIns(),
            NavMineFragment.obtainFragment()
        )
        viewBinding.viewpager.bindFragment(
            supportFragmentManager,
            fragmentList,
            pageChangeSelected = {

            })
        //界面禁止回收
        viewBinding.viewpager.offscreenPageLimit = fragmentList.size
        // 当ViewPager切换页面时，改变ViewPager的显示
    }


    private fun handleFlowBus() {
        //退出账号 时 切到第一个tab
        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            if (!UserDataCenter.isLogin() && (viewBinding.viewpager.currentItem != 0)) {
                mNavBar.indirectGoFirstBtn()
            }
            viewModel.loadHasNewSubs()
        }

        //切换到首页
        FlowBus.with<Boolean>(FlowConst.SWITCH_TO_HOME_PAGE).register(this) {
            mNavBar.indirectGoFirstBtn()
        }


        //跳到指定item
        FlowBus.with<Int>(FlowConst.WISH_INDEX_CHANGE).register(this) {
            mContext.navigation(path = RoutePage.Wishlist.WISHLIST_ENTRY)
        }

    }


    //外链 scheme协议拉起app↓
    //外链 scheme协议拉起app↓
    //外链 scheme协议拉起app↓
    private fun handleSchemeOrDeepLink(intent: Intent) {
        var uri = intent.data
        YYLogUtils.e("----handleSchemeOrDeepLink---$uri")
        uri?.let {
            YYLogUtils.e("----handleSchemeOrDeepLink---${uri.pathSegments}+---${uri.scheme}---${uri.host}")
            PullUpPageUtils.routePageIntercept4Url(
                activity = mActivity,
                url = it.toString(),
                externalPull = true
            )

            SpmTrackHandler.addSingleTrackData(
                SkAntEntity(
                    event = TrackEvent.appLifeCycle.value,
                    spmCnt = GTrackerAssistUtils.fetchElementValue(
                        0,
                        SpmElementDef.AppOpenFromLink
                    ),
                    params = mapOf("url" to it.toString())
                )
            )

        }
    }


    /**
     * 两次返回退出程序
     */
    private var firstTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        val secondTime = System.currentTimeMillis()
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (viewBinding.viewpager.currentItem != 0) {
                mNavBar.indirectGoFirstBtn()
                mNavBar.btmNavShowOrHide(true)
            } else {
                if (secondTime - firstTime < 2000) {
                    GuangAppStateManager.trackAppExist()
                    BridgeUtil.sendCommonData(BridgeCommand.Common.exitApp, "", true)
                    intentStart?.let {
                        //停止服务
                        stopService(it)
                    }
                    exitProcess(0)
                } else {
                    toast("Press again to exit the program")
                    firstTime = System.currentTimeMillis()
                    mNavBar.btmNavShowOrHide(true)
                }
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun startSpmService() {
        intentStart = Intent(
            this@MainActivity,
            SpmUploadService::class.java
        )
        startService(intentStart)
    }


    //-----------------------站点处理 开始---------------------------------
    var isFront = false

    //首页切换站点
    private fun handleSiteDialog() {
        FlowBus.with<Boolean>(FlowConst.SWITCH_SITE).register(this) {
            //什么时候国家发生了改变 在CountryApolloInterceptor拦截器里，切一次就置为false
            //每次只执行一次
            if (!BaseSiteSwitch.homeSiteDialog) {
                BaseSiteSwitch.homeSiteDialog = true
                viewModel.getSite { site ->
                    //读取成功,以当前ip为准
                    //失败，默认为美国IP，因为当前版本主推美国
                    if (site?.code != null && site.type != null && site.countryCode != null) {
                        if (!isFront) {
                            ActivityStackManage.toMainActivity()
                        }
                        //弹个框
                        showSitePopView(site)
                    } else {
                        BaseSiteSwitch.homeSiteDialog = false
                    }
                }
            }
        }
    }

    override fun onPause() {
        isFront = false
        super.onPause()
    }

    /**
     * 站点弹窗
     */
    private fun showSitePopView(site: SiteVOF) {
        viewBinding.siteLayout.siteCover.visible()
        viewBinding.siteLayout.siteCover.click {
        }
        viewBinding.siteLayout.siteCountryCode.text = site.countryCode
        viewBinding.siteLayout.siteOk.click {
            BaseSiteSwitch.homeSiteDialog = false
            BaseSiteSwitch.startUpPageSwitchSite(site)
            viewBinding.siteLayout.siteCover.gone()
            ActivityStackManage.killAppAndRestart()
        }
    }

    //-----------------------站点处理 结束---------------------------------

    //----------------------初始化通知 开始---------------------------------
    /**
     * 初始化通知相关内容
     */
    override fun initNotification() {
        // API level >= 26时，显示通知需要创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = getString(R.string.default_notification_channel_id)
            val channelName = getString(R.string.default_notification_channel_name)
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager?.createNotificationChannel(
                NotificationChannel(
                    channelId,
                    channelName, NotificationManager.IMPORTANCE_HIGH
                )
            )
        }
        FCMUtils.syncFcmToken()

        //不切换站点时申请通知权限,需要切换站点时会重启，还会重新走这一步
        //!SpmTrackHandler.siteStatusHasSwitch &&
        if (SkNoviceManage.canShowGuide(SkGuideEnum.HOME_FRG_NOTIFY_PERMISSION_V2)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                showNotifyView(true, actionClick = {
                    SkNoviceManage.hasPopGuide(SkGuideEnum.HOME_FRG_NOTIFY_PERMISSION_V2)
                    requestNotificationPermissions()
                })
            } else {
                SkNoviceManage.hasPopGuide(SkGuideEnum.HOME_FRG_NOTIFY_PERMISSION_V2)
                notifyPopNextGuide()
            }
        }else{
            notifyPopNextGuide()
        }
    }


    private fun notifyPopNextGuide() {
        FlowBus.boolFlowBusNotify(FlowConst.HOME_GUIDE_NEXT)
    }

    private val requestPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
            if (isGranted) {
                SKLogger.e("dss", "POST_NOTIFICATIONS已授权")
                notifyPopNextGuide()
            } else {
                // Inform user that that your app will not show notifications.
                SKLogger.e("dss", "POST_NOTIFICATIONS未授权")
                notifyPopNextGuide()
            }
        }

    /**
     * 请求通知权限
     */
    private fun requestNotificationPermissions() {
        // API level >= 33时，无通知权限不显示通知
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    android.Manifest.permission.POST_NOTIFICATIONS
                ) ==
                PackageManager.PERMISSION_GRANTED
            ) {
                notifyPopNextGuide()
                SKLogger.e("dss", "POST_NOTIFICATIONS已授权")
            } else {
                // Directly ask for the permission
                requestPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    }


    private fun showNotifyView(
        show: Boolean,
        actionClick: (type: Int) -> Unit
    ) {
        if (show) {
            viewBinding.notifyLayout.notifyCover.visible()
            viewBinding.notifyLayout.notifyOk.click {
                viewBinding.notifyLayout.notifyCover.gone()
                actionClick.invoke(1)
            }
            viewBinding.notifyLayout.notifyCover.click {
                viewBinding.notifyLayout.notifyCover.gone()
                actionClick.invoke(3)
            }
        } else {
            viewBinding.notifyLayout.notifyCover.gone()
        }
    }

    //----------------------初始化通知 结束---------------------------------

}